import { createRouter, createWebHashHistory, createWebHistory } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
import { useSysconfigrStore } from "@/stores/modules/sysconfig";
import { useTokenStore } from "@/stores/modules/token";
import { useAuthStore } from "@/stores/modules/auth";
import { LOGIN_URL, ROUTER_WHITE_LIST } from "@/config";
import { staticRouter, homeRouter, errorRouter } from "@/routers/modules/staticRouter";
import AsyncRoutes from "../routers/modules/index";
import NProgress from "@/config/nprogress";
import { getSysConfig } from "@/api/modules/system";
import { SYSTEM_CONFIG } from "@/config/system";
import { PAGES_CONFIG } from "@/config/pages";
import { getUrlParams } from "@/utils/common";

const mode = import.meta.env.VITE_ROUTER_MODE;

const routerMode = {
  hash: () => createWebHashHistory(),
  history: () => createWebHistory()
};

/**
 * @description 📚 路由参数配置简介
 * @param path ==> 路由菜单访问路径
 * @param name ==> 路由 name (对应页面组件 name, 可用作 KeepAlive 缓存标识 && 按钮权限筛选)
 * @param redirect ==> 路由重定向地址
 * @param component ==> 视图文件路径
 * @param meta ==> 路由菜单元信息
 * @param meta.icon ==> 菜单和面包屑对应的图标
 * @param meta.title ==> 路由标题 (用作 document.title || 菜单的名称)
 * @param meta.activeMenu ==> 当前路由为详情页时，需要高亮的菜单
 * @param meta.isLink ==> 路由外链时填写的访问地址
 * @param meta.isHide ==> 是否在菜单中隐藏 (通常列表详情页需要隐藏)
 * @param meta.isFull ==> 菜单是否全屏 (示例：数据大屏页面)
 * @param meta.isAffix ==> 菜单是否固定在标签页中 (首页通常是固定项)
 * @param meta.isKeepAlive ==> 当前路由是否缓存
 * */
const router = createRouter({
  history: routerMode[mode](),
  routes: [...staticRouter, ...homeRouter, ...AsyncRoutes, ...errorRouter],
  strict: false,
  scrollBehavior: () => ({ left: 0, top: 0 })
});

/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  const sysConfigState = useSysconfigrStore();
  const tokenStore = useTokenStore();
  const authStore = useAuthStore();
  /**NProgress 开始 */
  NProgress.start();
  if (!sysConfigState.appId) {
    /**系统信息接口 */
    const configData: any = await getSysConfig();
    /**设置系统配置 */
    sysConfigState.setSysConfig(configData.data);
  }
  // 如果进入login或者sso页面不需要存储
  if (to.fullPath !== PAGES_CONFIG.LOGIN_URL && to.path !== PAGES_CONFIG.LOGOUT_URL && to.fullPath !== PAGES_CONFIG.SSO_URL) {
    /**存储 routerName 做按钮权限筛选 */
    authStore.setRouteName(to.name as string);
  }
  /**动态设置标题 */
  const title = SYSTEM_CONFIG.APP_NAME;
  document.title = to.meta.title ? `${to.meta.title} - ${title}` : title;
  /**获取token */
  const accessToken = tokenStore.access_token;
  /**判断ststemconfig登录类型 */
  if (sysConfigState.loginType === "TOKEN") {
    if (accessToken) {
      if (to.path === PAGES_CONFIG.LOGIN_URL || to.path === PAGES_CONFIG.LOGOUT_URL || to.path === PAGES_CONFIG.SSO_URL) {
        // 如果已经登录了 则到首页
        next({ path: "/" });
        // 关闭进度条
        NProgress.done();
      } else {
        // 获取vuex中的用户信息
        const hasUserId = userStore.userId;
        if (hasUserId) {
          next();
        } else {
          try {
            /**获取用户信息 */
            await userStore.getInfo();
            /**获取菜单 */
            await authStore.getAuthMenuList();
            next({ ...to, replace: true });
          } catch (error) {
            tokenStore.clearToken();
            next({ path: PAGES_CONFIG.LOGIN_URL, query: { redirect: to.path } });
          }
        }
      }
    } else {
      if (to.path === PAGES_CONFIG.LOGIN_URL || to.path === PAGES_CONFIG.LOGOUT_URL) {
        next();
      } else {
        next({ path: PAGES_CONFIG.LOGIN_URL, query: { redirect: to.path } });
      }
    }
  } else if (sysConfigState.loginType === "THIRD") {
    console.log("THIRD");
  } else if (sysConfigState.loginType === "TOKENANDTHIRD") {
    if (accessToken) {
      if (to.path === PAGES_CONFIG.LOGIN_URL || to.path === PAGES_CONFIG.LOGOUT_URL || to.path === PAGES_CONFIG.SSO_URL) {
        next({ path: "/" });
        NProgress.done();
      } else {
        const hasUserId = userStore.userId;
        if (hasUserId) {
          next();
        } else {
          try {
            /**获取用户信息 */
            await userStore.getInfo();
            /**获取菜单 */
            await authStore.getAuthMenuList();
            next({ ...to, replace: true });
          } catch (error) {
            tokenStore.clearToken();
            next({ path: PAGES_CONFIG.LOGIN_URL, query: { redirect: to.path } });
          }
        }
      }
    } else if (getUrlParams(SYSTEM_CONFIG.SSO_LOGIN_KEY)) {
    } else {
      if (to.path === PAGES_CONFIG.LOGIN_URL || to.path === PAGES_CONFIG.LOGOUT_URL || to.path === PAGES_CONFIG.SSO_URL) {
        next();
      } else {
        next({ path: PAGES_CONFIG.LOGIN_URL, query: { redirect: to.path } });
      }
    }
  } else {
    //其他类型先直接返回吧
    next();
  }
});

/**重置路由 */
export const resetRouter = () => {
  const authStore = useAuthStore();
  authStore.flatMenuListGet.forEach(route => {
    const { name } = route;
    if (name && router.hasRoute(name)) router.removeRoute(name);
  });
};

/**路由跳转错误 */
router.onError(error => {
  NProgress.done();
  console.warn("路由错误", error.message);
});

/**路由跳转结束 */
router.afterEach(() => {
  NProgress.done();
});

export default router;
